

var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var validate = utils.validate;
var SqlHelper = utils.SqlHelper;
var dateHelper = require('../../utils/date.js')
// var Queue = require('../../utils/Queue.js')
var jwt = require('../../utils/jwt.js')

// 信息remark
const remark = "dangdao0419"

// 开始结束时间
// const startDate = new Date("2018.4.20");
// const endDate = new Date("2018.4.22 12:00");

const startDate = new Date("2018.1.1");
const endDate = new Date("2019.4.22 12:00");


let decipher = function (cipherNum) {
    var cipher = parseInt(cipherNum, 16).toString();
    var score = parseInt(cipher.substr(13));
    return score / 100;
}

var setScore = async function (req, res) {


    let body = req.body;

    // ------ 活动时间确认
    let nowDate = new Date();
    if (nowDate < startDate) {
        return res.send({ error_code: 1, msg: '活动还未开始!' });
    }
    if (nowDate >= endDate) {
        return res.send({ error_code: 1, msg: '活动已经结束!' });
    }

    // ------ 参数检查
    if (!body.token || !body.nickname || !body.headurl || !body.score_base) {
        return res.send({ error_code: 1, msg: '无效请求, 参数错误' });
    }

    // ----- token解析
    let tokenData = await jwt.decode(body.token);
    if (!tokenData || !tokenData.userid) {
        return res.send({ error_code: 1, msg: '无效请求, token error' });
    }

    // ----- 上传分数
    try {
        let sqlHelper = new SqlHelper('gamerank_dangdai0419');
        var score = decipher(body.score_base);

        // 获取数据
        let userInfo = await sqlHelper.asyncSelect({ openid: tokenData.userid });
        if (userInfo.length > 0) {
            if(userInfo[0].score > score){ // 记录最大值即可
                return res.send({ state: 1 });
            }
            let result = await sqlHelper.asyncUpdate({ openid: tokenData.userid }, { nickname: body.nickname, headurl: body.headurl, score: score });
            return res.send({ state: 1 });
        } else {
            let result = await sqlHelper.asyncInsert({ openid: tokenData.userid, nickname: body.nickname, headurl: body.headurl, score: score });
            return res.send({ state: 1 });
        }


    } catch (error) {
        return res.send({ error_code: 1, msg: error.message });
    }

}

// var setInfo = async function (req, res) {
//     var body = req.body || req.query;

//     if (!body.token) {
//         return res.send({ error_code: 1001, msg: '无效请求, token error' });
//     }

//     // 授权确认
//     var tokenData = await jwt.decode(body.token);
//     if (!tokenData || !tokenData.userid) {
//         return res.send({ error_code: 1001, msg: '无效请求, token error' });
//     }

//     // 信息完整性检查
//     if (!validate.isName(body.name)) {
//         return res.send({ state: 2 });
//     }
//     if (!validate.isPhone(body.phone)) {
//         return res.send({ state: 3 });
//     }


//     let sqlHelper = new SqlHelper('checkin');
//     let isHas = await sqlHelper.asyncCheckExist({ openid: tokenData.userid, remark: remark });
//     if (isHas) {
//         let result1 = await sqlHelper.asyncUpdate({ openid: tokenData.userid, remark: remark }, { name: body.name, phone: body.phone });
//         return res.send({ state: 1 });
//     } else {
//         let result1 = await sqlHelper.asyncInsert({ openid: tokenData.userid, remark: remark, name: body.name, phone: body.phone });
//         return res.send({ state: 1 });
//     }

// }

var getRank = async function (req, res) {
    let body = req.body || req.query;

    if (!body.token) {
        return res.send({ error_code: 1001, msg: '无效请求, token error' });
    }

    // 授权确认
    let tokenData = await jwt.decode(body.token);
    if (!tokenData || !tokenData.userid) {
        return res.send({ error_code: 1001, msg: '无效请求' });
    }

    let sqlHelper = new SqlHelper('gamerank_dangdai0419');

    let page_num = 7;
    let page_index = 0;
    if (body.page_num) {
        page_num = body.page_num;
    }
    if (body.page_index) {
        page_index = body.page_index;
    }

    try {

        // 获取rank列表
        let sqlStr = 'SELECT  @curRank := @curRank + 1 AS rank ,openid, nickname, score, headurl FROM gamerank_dangdai0419 r,(SELECT @curRank := 0) t ORDER BY score';
        sqlStr = sqlStr + ' limit ' + (page_index * page_num) + ',' + page_num + ';';

        // 获取自己排行记录
        var result = await sqlHelper.asyncQuery(sqlStr);


        let sqlStr2 = 'SELECT * from (SELECT  @curRank := @curRank + 1 AS rank ,openid, nickname, headurl FROM gamerank_dangdai0419 r,(SELECT @curRank := 0) t ORDER BY score ) a where openid = '
        sqlStr2 = sqlStr2 + '"' + tokenData.userid + '";';

        var result2 = await sqlHelper.asyncQuery(sqlStr2);

        return res.send({ state: 1, ranks: result, myinfo: result2[0] });

    } catch (error) {
        return res.send({ error_code: 1, msg: error.message });
    }

}


var analysisFn = function (req, res, next) {
    var body = req.body;

    switch (req.query.cmd) {
        case 'setScore':  // 上传分数
            setScore(req, res)
            break;
        case 'getRank':
            getRank(req, res);  // 获取排行榜
            break;
        // case 'setInfo':
        //     setInfo(req, res);  // 设置信息，领奖
        //     break;
        default:
            return res.send({ error_code: 1001, msg: '无效请求, cmd参数出错' });
    }
}

server.post({ path: routerApi, name: routerApi }, analysisFn)